package com.hmsm.sys.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlgraphics.java2d.color.DeviceCMYKColorSpace;
import org.springframework.stereotype.Service;

import com.hmsm.dingtalk.Department;
import com.hmsm.dingtalk.DingTalkClient;
import com.hmsm.dingtalk.User;
import com.hmsm.rtx.RTXClient;
import com.hmsm.rtx.RTXDept;
import com.hmsm.server.base.BaseService;
import com.hmsm.server.common.AppContextService;
import com.hmsm.server.util.QueryResult;
import com.hmsm.sys.bean.DeptTypeEnum;
import com.hmsm.sys.bean.LocalDept;
import com.hmsm.sys.bean.LocalRole;
import com.hmsm.sys.bean.LocalUser;
import com.hmsm.sys.bean.RTXDeptBean;
import com.hmsm.sys.bean.RTXUserBean;
import com.hmsm.sys.bean.RelevanceConfig;
import com.hmsm.sys.dao.DeptInfoDao;
import com.hmsm.sys.dao.OrgInfoDao;
import com.hmsm.sys.po.DeptInfo;
import com.hmsm.sys.po.OrgDeptLevel;
import com.hmsm.sys.po.OrgInfo;
import com.hmsm.sys.po.OrgType;
import com.hmsm.sys.po.RoleInfo;
import com.hmsm.sys.po.UserInfo;
import com.hmsm.sys.po.UserOrg;
import com.lzyyj.common.Page;
import com.lzyyj.gmis.base.dao.IBaseDao;
import com.lzyyj.gmis.base.model.Purview;
import com.lzyyj.gmis.base.service.IHaveRoleFuncs;
import com.lzyyj.gmis.base.service.IModuleService;

@Service
public class DeptInfoService extends BaseService<DeptInfo, Integer, UserInfo, RoleInfo> implements IOrgService<DeptInfo>,IModuleService,IHaveRoleFuncs,IDeptInfoService<DeptInfo> {

	@Resource(name="orgTypeDao")
	private IBaseDao<OrgType, Integer> orgTypeDao ;

	@Resource(name="orgDeptLevelDao")
	private IBaseDao<OrgDeptLevel, Integer> orgDeptLevelDao ;
	
	@Override
	public boolean delete(DeptInfo deptInfo) throws Exception {
		deptInfo.setState(0);
		deptInfo = update(deptInfo);
		return super.delete(deptInfo);
	}

	private static final Log log = LogFactory.getLog(DeptInfoService.class);
	
	public DeptInfoDao getDeptInfoDao() {
		return (DeptInfoDao) baseDao;
	}

	public void setDeptInfoDao(DeptInfoDao baseDao) {
		this.baseDao = baseDao;
	}
	
	@Resource
	private OrgInfoDao orgInfoDao;

	public OrgInfoDao getOrgInfoDao() {
		return orgInfoDao;
	}

	public void setOrgInfoDao(OrgInfoDao orgInfoDao) {
		this.orgInfoDao = orgInfoDao;
	}

	@Resource
	private UserOrgService userOrgService;

	public UserOrgService getUserOrgService() {
		return userOrgService;
	}

	public void setUserOrgService(UserOrgService userOrgService) {
		this.userOrgService = userOrgService;
	}

	public static final String ORG_ADMIN = "组织机构管理员";
	public static final String ORG_DEPT_ADMIN = "部门理员";
	
	private static final List<Purview> funcGroup = new ArrayList<Purview>();
	
	@Override
	public List<Purview> getFuncGroup(){
		return funcGroup;
	}

	private static final List<String> roleList = new ArrayList<String>();
	
	@Override
	public List<String> getRoleList(){
		return roleList;
	}
	
	@Override
	public String getAdminRole() {
		// 声明业务管理角色
//		return ORG_ADMIN;
		return null;
	}

	public static final Map<String, String[]> roleFuncs = new HashMap<String, String[]>();
	
	@Override
	public Map<String, String[]> getRoleFuncs() {
		return roleFuncs;
	}
	
	public DeptInfoService(){
		
		// 声明需注册的功能权限
		Purview mainPurview = new Purview("系统管理", RIGHT_SYS_GROUP, "管理系统基本配置");
		List<Purview> purvies = mainPurview.getPurviews();
		
		Purview purview = new Purview("组织机构管理", RIGHT_ORG_MANAGE, "管理组织机构"); 
		purvies.add(purview);
		
		List<Purview> rangeList = purview.getPurviews();
		rangeList.add(new Purview("所属部门的", RIGHT_RANGE_ORG_DEPT, "所属部门范围内的"));
		rangeList.add(new Purview("所属组织机构的", RIGHT_RANGE_ORG_ORG, "所属组织机构范围内的"));
		rangeList.add(new Purview("所有的", RIGHT_RANGE_ORG_ALL, "管理所有组织机构"));
		
		funcGroup.add(mainPurview);

		// 声明系统的组织机构管理员角色，并设置默认权限
		roleList.add(ADMIN_ROLE_NAME);
		roleFuncs.put(ADMIN_ROLE_NAME, new String[]{
				RIGHT_ORG_MANAGE+"("+RIGHT_RANGE_ORG_DEPT+","+RIGHT_RANGE_ORG_ORG+","+RIGHT_RANGE_ORG_ALL+")"
		});
		
	}
	
	@Override
	public String getModuleName(){
		return "组织机构管理";
	}

	@Override
	public void start() {
	}

	@Override
	public void stop() {
	}

	@Override
	public DeptInfo getNew() {
		DeptInfo newDeptInfo = new DeptInfo();
		return newDeptInfo;
	}

	public DeptInfo getNew(DeptInfo example) {
		return example;
	}

	@Override
	public DeptInfo getById(Integer id) {
		return getById(id, false); 
	}

	/**
	 * 是否要包含已删除部门
	 * @param id
	 * @param includeDel
	 * @return
	 */
	public DeptInfo getById(Integer id, boolean includeDel) {
		DeptInfo deptInfo = null;
		if (id!=null&&id==0){
			deptInfo = new DeptInfo();
			deptInfo.setPkId(0);
			deptInfo.setOrgId(0);
			deptInfo.setState(1);
			deptInfo.setName("组织机构");
		}else{
			deptInfo = (DeptInfo)super.getById(id);
			if (deptInfo!=null){
				if (!includeDel){
					if (deptInfo.getState()==null||deptInfo.getState()!=1){
						deptInfo = null;
					}
				}
			}
		}
		if (deptInfo!=null){
			deptInfo.setOrg(getOrgInfoById(deptInfo.getOrgId()));
		}
		return deptInfo;
	}

	/**
	 * 根据组织机构ID，获取营业厅
	 * @param orgId
	 * @return
	 * @author 张帅
	 */
	public List<DeptInfo> getDeptByOrgId(int orgId){
		DeptInfo d = new DeptInfo();
		d.setState(1);
		d.setOrgId(orgId);
		d.setSubDepts(null);
		d.setUsers(null);
		return getDeptInfoDao().query(d);
	}

	public DeptInfo save(DeptInfo deptVo) throws Exception{
		return save((DeptInfo)deptVo, null);
	}

	/**
	 * 保存部门，(修改属性列表指定属性)
	 * @param deptVo
	 * @param propertyList
	 * @return
	 * @throws Exception
	 */
	public DeptInfo save(DeptInfo deptVo, String propertyList) throws Exception{
		
		boolean orgChanged = false;
		
		if (propertyList==null){
			propertyList = "name,parent,idType";
		}
		String _propertyList = propertyList;

		DeptInfo deptPo = null;
		if (deptVo.getPkId()!=null&&deptVo.getPkId()>0){
			deptPo = getById(deptVo.getPkId());
		}else{
			deptPo = (DeptInfo) getNew(deptVo);
		}
		
		if ((","+_propertyList+",").contains(",relevanceConfig,")){
			deptPo.setRelevanceConfig(deptVo.getRelevanceConfig());
		}
		
		if ((","+_propertyList+",").contains(",parId,")){
			deptPo.setParId(deptVo.getParId());
		}
		
		if ((","+_propertyList+",").contains(",parent,")){
			if (deptVo.getParent()!=null){
				deptVo.setParId(deptVo.getParent().getPkId());
			}else{
				deptVo.setParId(null);
			}
			deptPo.setParId(deptVo.getParId());
			_propertyList = (","+_propertyList+",").replace(",parent,", ",parId,").substring(1);
		}
		
		if ((","+_propertyList+",").contains(",name,")){
			if(!isUnique(deptVo, "parId,name")){
				throw new Exception("名称有重复！");
			}
			deptPo.setName(deptVo.getName());
		}
		
		if ((","+_propertyList+",").contains(",deptType,")){
			orgChanged = deptPo.isOrganization() ^ deptVo.isOrganization();
			deptPo.setDeptType(deptVo.getDeptType());
		}
		
		if ((","+_propertyList+",").contains(",deptNo,")){
			deptPo.setDeptNo(deptVo.getDeptNo());
		}
		
		if ((","+_propertyList+",").contains(",idType,")){
			deptPo.setIdType(deptVo.getIdType());
		}
		
		if ((","+_propertyList+",").contains(",type,")){
			deptPo.setType(deptVo.getType());
		}
		
		OrgInfo orgPo = null;
		boolean setOrgRootDept = true;
		if (deptPo.getPkId()==null||deptPo.getPkId()==0){
			// 是新建部门，查询是否有所属组织机构
			
			// 是否是组织机构
			if (deptPo.isOrganization()){
				// 是作为组织机构的，需要新建组织机构信息
				orgPo = findOrgInfo(deptVo, true);
				orgPo.setName(deptVo.getOrg().getName());
				if (orgPo.getName()==null||orgPo.getName().length()==0){
					orgPo.setName(deptVo.getName());
				}
				orgPo.setRootDept(null);
				setOrgRootDept = false;
				orgPo = saveOrgInfo(orgPo);
				deptPo.setOrg(orgPo);
				deptPo.getOrg().setPkId(orgPo.getPkId());
				deptPo.setOrgId(orgPo.getPkId());
				orgChanged = true;
				if (!(","+propertyList+",").contains(",org.name")){
					if (propertyList.length()>0){
						propertyList += ",";
					}
					propertyList += "org.name";
				}
				orgPo.setName(deptVo.getOrg().getName());
				if ((","+_propertyList+",").contains(",org.orgType,")&&deptVo.getOrg().getOrgType()!=null){
					OrgType ortType = orgTypeDao.getById(deptVo.getOrg().getOrgType().getPkId());
					orgPo.setOrgType(ortType);
				}
			}else{
				// 不是组织机构
				DeptInfo parent = null;
				if (deptVo.getParent()!=null&&deptVo.getParent().getPkId()!=null&&deptVo.getParent().getPkId()>0){
					parent = getById(deptVo.getParent().getPkId());
				}
				
				if (parent==null||parent.getPkId()==null||parent.getPkId()==0){
					orgPo = getByRootDept(deptPo);
					if (orgPo!=null){
						deptPo.setOrg(orgPo);
						deptPo.setOrgId(orgPo.getPkId());
					}else{
						deptPo.setOrg(null);
						deptPo.setOrgId(0);
					}
				}else{
					deptPo.setOrgId(parent.getOrgId());
				}
			}
		}else{
			// 是更新，是否是组织机构呢？
			if (deptPo.isOrganization()){
				if (orgChanged){
					// 是更新，原来不是组织机构，现在已经是组织机构了
					// 构建新的组织描述
					orgPo = findOrgInfo(deptVo, true);
					orgPo.setName(deptVo.getOrg().getName());
					if (orgPo.getName()==null||orgPo.getName().length()==0){
						orgPo.setName(deptVo.getName());
					}
					orgPo.setRootDept(deptPo);
					orgPo = saveOrgInfo(orgPo);
					deptPo.setOrg(orgPo);
					deptPo.getOrg().setPkId(orgPo.getPkId());
					deptPo.setOrgId(orgPo.getPkId());
					orgChanged = true;
					if (!(","+propertyList+",").contains(",org.name")){
						if (propertyList.length()>0){
							propertyList += ",";
						}
						propertyList += "org.name";
					}
				}else{
					orgPo = getOrgInfoById(deptPo.getOrgId());
					if (orgPo==null){
						orgPo = findOrgInfo(deptVo, true);
						orgPo.setName(deptVo.getOrg().getName());
						if (orgPo.getName()==null||orgPo.getName().length()==0){
							orgPo.setName(deptVo.getName());
						}
						orgPo.setRootDept(deptPo);
						orgPo = saveOrgInfo(orgPo);
						deptPo.setOrg(orgPo);
						deptPo.getOrg().setPkId(orgPo.getPkId());
						deptPo.setOrgId(orgPo.getPkId());
						orgChanged = true;
					}
					if (!(","+propertyList+",").contains(",org.name")){
						if (propertyList.length()>0){
							propertyList += ",";
						}
						propertyList += "org.name";
					}
				}
				orgPo.setName(deptVo.getOrg().getName());
				if ((","+_propertyList+",").contains(",org.orgType,")&&deptVo.getOrg().getOrgType()!=null){
					OrgType ortType = orgTypeDao.getById(deptVo.getOrg().getOrgType().getPkId());
					orgPo.setOrgType(ortType);
				}
			}else{
				// 是更新，不是组织机构
				if(orgChanged){
					// 是更新，原来是组织机构，现在已不是组织机构了
					orgPo = findOrgInfo(deptPo, false);
					if (orgPo!=null){
						deleteOrgInfo(orgPo);
						orgPo = null;
					}
					if (deptPo.getParent()==null){
						deptPo.setOrg(null);
						deptPo.setOrgId(0);
					}else{
						try {
							orgPo = getOrgInfoById(deptPo.getParent().getOrgId());
						} catch (Exception e) {
							orgPo = null;
						}
						if (orgPo!=null){
							deptPo.setOrg(orgPo);
							if (!(","+propertyList+",").contains(",org")){
								if (propertyList.length()>0){
									propertyList += ",";
								}
								propertyList += "org";
							}
						}else{
							deptPo.setOrgId(0);
							if (!(","+propertyList+",").contains(",orgId")){
								if (propertyList.length()>0){
									propertyList += ",";
								}
								propertyList += "orgId";
							}
						}
					}
				}else{
					// 是更新，不是组织机构
					if ((","+propertyList+",").contains("org.name")){
						propertyList = (","+propertyList+",").replace(",org.name", "");
						if (propertyList.startsWith(",")){
							propertyList = propertyList.substring(1);
						}
						if (propertyList.endsWith(",")){
							propertyList = propertyList.substring(0,propertyList.length()-1);
						}
					}
				}
			}
		}

		// 检查必填项
		if (deptPo.getDeptType()==null){
			deptPo.setDeptType(0);
		}
		if (deptPo.getIdType()==null){
			deptPo.setIdType(0);
		}
		if (deptPo.getType()==null){
			deptPo.setType(0);
		}
		if (deptPo.getLevel()==null){
			deptPo.setLevel(deptPo.getRealLevel());
		}

		// 检查重名，如有，合并重名对象及其相关业务关系
		if (deptPo.getPkId()==null||deptPo.getPkId()==0){
			deptPo = (DeptInfo) baseDao.save(deptPo);
		}else{
			deptPo = (DeptInfo) baseDao.update(deptPo);
		}
		if (orgPo!=null){
			if(!setOrgRootDept){
				orgPo.setRootDept(deptPo);
			}
			updateOrgInfo(orgPo);
		}

		if (orgChanged){
			updateOrgId(deptPo);
		}
		
		return deptPo;
	}
	
	@Override
	public DeptInfo update(DeptInfo deptInfoVo){
		if(deptInfoVo.getDeptType()==null){
			deptInfoVo.setDeptType(0);
		}
		if(deptInfoVo.getType()==null){
			deptInfoVo.setType(0);
		}
		return baseDao.update(deptInfoVo);
	}
	
	public boolean isUnique(DeptInfo entityVo, String propertyList) {
		return getDeptInfoDao().isUnique(entityVo, propertyList);
	}

	private void updateOrgId(DeptInfo deptInfoPo) {
		Integer orgId = deptInfoPo.getOrgId();
		loadSubDepts(deptInfoPo);
		for(DeptInfo subDept:deptInfoPo.getSubDepts()){
			if (!subDept.isOrganization()){
				subDept.setOrgId(orgId);
				try {
					super.update((DeptInfo)subDept);
				} catch (Exception e) {
					e.printStackTrace();
				}
				updateOrgId((DeptInfo)subDept);
			}
		}
		// 更新所有下级部门的组织机构
		List<UserInfo> users = deptInfoPo.getUsers();
		if (users==null){
			users = new ArrayList<UserInfo>();
			deptInfoPo.setUsers(users);
		}
		
		List<UserOrg> userOrgs = userOrgService.getUserOrgListByDeptId(deptInfoPo.getPkId());
		if (userOrgs!=null){
			for(UserOrg userOrg:userOrgs){
				Integer userId = userOrg.getUserId();
				UserInfo userInfo = getUserInfoService().getById(userId);
				if (userInfo!=null){
					users.add(userInfo);
					userInfo.setDepart(deptInfoPo);
					try {
						getUserInfoService().update(userInfo, "userDept");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				userOrg.setOrgId(orgId);
				userOrgService.update(userOrg);
			}
		}
	}

	/**
	 * 根据组织机构ID，获取所有的部门
	 * @param orgId
	 * @return
	 * @author 舒俊
	 */
	public List<DeptInfo> getDeptInfoByOrgid(Integer orgId){
		DeptInfo d = new DeptInfo();
		d.setState(1);
		d.setOrgId(orgId);
		return getDeptInfoDao().query(d);
	}
	
	/**
	 * 获取指定部门的下级部门列表
	 * @param orgId
	 * @return
	 * @author 袁勇军
	 */
	public void loadSubDepts(DeptInfo parent){
		loadSubDepts((DeptInfo) parent, 1);
	}
	
	/**
	 * 获取指定部门的下级部门列表
	 * @param orgId
	 * @return
	 * @author 袁勇军
	 */
	public void loadSubDepts(DeptInfo parent, int depth){
		loadSubDepts(parent, "", depth);
	}

	/**
	 * 加载子部门及列表指定的属性值
	 * @param deptInfo
	 * @param propertyList
	 * @param depth
	 */
	@Override
	public void loadSubDepts(DeptInfo deptInfo, String propertyList, int depth) {
		if (deptInfo!=null&&(depth==-1||depth>0)){
			DeptInfo example = new DeptInfo();
			example.setState(1);
			example.setParId(deptInfo.getPkId());
			List<DeptInfo> subDepts = deptInfo.getSubDepts();
			if (subDepts==null){
				subDepts = new ArrayList<DeptInfo>();
				deptInfo.setSubDepts(subDepts);
			}else{
				subDepts.clear();
			}
			
			List<DeptInfo> list = getDeptInfoDao().query(example, "deptNo");
			for(DeptInfo subDept :list){
				subDept.setParent(deptInfo);
				subDepts.add(subDept);
			}
			
			if(propertyList!=null&&(","+propertyList+",").contains(",users,")){
				// 加载部门用户
				loadUsers((DeptInfo)deptInfo);
			}
			if (depth==-1||depth>0){
				for (DeptInfo subDept:subDepts){
					loadSubDepts(subDept, propertyList, depth==-1?-1:depth-1);
				}
			}
		}
	}
	
	/**
	 * 获取指定部门的下级部门列表
	 * @param orgId
	 * @return
	 * @author 舒俊
	 */
	public List<DeptInfo> getSubDeptsByParentId(Integer parentId){
		DeptInfo d = new DeptInfo();
		d.setState(1);
		d.setParId(parentId);
		return this.getDeptInfoDao().query(d, "deptNo");
	}
	
	/**
	 * 获取部门 记录
	 * 根据父部门ID获取部门列表
	 * @param parId
	 * @return
	 * @author 舒俊
	 */
	public List<DeptInfo> getPartDept(int parId){
		DeptInfo d = new DeptInfo();
		d.setState(1);
		d.setParId(parId);
		return this.getDeptInfoDao().query(d);
	}
	
	/**
	 * 获取用户 记录
	 * @param index 当前页
	 * @param maxresult 每页数量 
	 * @param 
	 * @return
	 */	
	public QueryResult<DeptInfo> getOrgInfoAll(Integer index,
			Integer maxresult, String name, Integer parId) {
		
		String whererjpql="  1=1 and o.state=1 ";
        List<Object> lst = new ArrayList<Object>();
        if (name != null && !name.trim().equals(""))
        {
            whererjpql = whererjpql + " and o.name  like ?";
            lst.add("%"+name+"%");
        }
        if (parId != null)
        {
            whererjpql = whererjpql + " and o.parId  = ?";
            lst.add(parId);
        }
        LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
        orderby.put("pkId","asc");
        return this.getDeptInfoDao().getScrollData(DeptInfo.class, "pkId", index,
                maxresult, whererjpql, lst.toArray(),orderby);
	}		
	
	public String getOrgName(Integer oid) {		
		OrgInfo o = getOrgInfoDao().getById(oid);
		return o.getName();
	}
	
	/**
	 * 获取部门地址
	 * @param deptId
	 * @return
	 * @author 舒俊
	 */
	public String getDeptAllInfo(int deptId){
		DeptInfo dept = (DeptInfo) this.getById(deptId);
		String str = null;
		boolean flag = true;
		while(flag){
			if(dept.getParId()==0){
				flag = false;
			}
			if(str==null){
				str = dept.getName();
			}else{
				str = dept.getName() + ">"+str;;
			}
			dept =  this.getById(dept.getParId());
		}
		return str;
	}
	
	/**
	 * 获取所有部门信息
	 * @return
	 * @author 何杰 2013-2-21
	 */
	public List<DeptInfo> getAllDept(){
		return this.getDeptInfoDao().getAllDept();
	}
	
	/**
	 * 根据腾讯通ID获取部门信息
	 * @param rtxId
	 * @return
	 * @author 何杰 2013-2-22
	 */
	public DeptInfo getDeptByRtxId(int rtxId){
		return getDeptInfoDao().getDeptByRtxId(rtxId);
	}
	
	/**
	 * 根据类型获取该组织机构下的所有部门
	 * @param orgId
	 * @param type
	 * @return
	 * @author 舒俊
	 */
	public List<DeptInfo> getDeptInfoByOrgidAndType(int orgId,Integer type){
		DeptInfo d = new DeptInfo();
		d.setState(1);
		d.setOrgId(orgId);
		if(type!=null){
			d.setType(type);
		}
		return this.getDeptInfoDao().query(d);
	}
	/**
	 * 获取所有营业厅(有效)
	 * @return
	 * @author luoc 
	 * @serialData 2013-08-31
	 */
	public List<DeptInfo> getAllDeptInfoList(){
		
		return this.getDeptInfoDao().getAllDeptInfoList();
		
	}
	/**
	 * 获取所有营业厅(包括无效)
	 * @return
	 * @author luoc 
	 * @serialData 2013-08-31
	 */
	public List<DeptInfo> getAllAndNoDeptInfoList(){
		
		return this.getDeptInfoDao().getAllAndNoDeptInfoList();
		
	}
	
	/**
	 * 递归删除该部门下的所有用户和机构信息
	 * @param dept
	 * @throws Exception 
	 */
	public void deleteDeptAndUserAll(DeptInfo dept) throws Exception{
		if(dept==null){
			return;
		}
		//获取该部门的用户
		List<UserOrg> uoAll = AppContextService.getUserOrgService().getUserOrgListByDeptId(dept.getPkId());
		for(int i=0;i<uoAll.size();i++){
			UserOrg uo =uoAll.get(i);
			//获取用户
			getUserInfoService().deleteById(uo.getUserId());
		}
		//获取该机构的子部门
		List<DeptInfo> deptAll = this.getPartDept(dept.getPkId());
		for(int i=0;i<deptAll.size();i++){
			deleteDeptAndUserAll(deptAll.get(i));
		}
		dept.setState(2);
		this.update(dept);
	}

	/**
	 * 获取指定组织机构下的部门选择树列表
	 * @throws Exception 
	 */
	public List<DeptInfo> getDeptSelectList(Integer orgId) throws Exception{
		List<DeptInfo> list = new ArrayList<DeptInfo>();
		
		OrgInfo org;
		DeptInfo rootDept;
		if (orgId!=null&&orgId>0){
			org = getOrgInfoDao().getById(orgId);
			
		}else{
			org = null;
		}
		if (org!=null&&org.getState()==1){
			rootDept = org.getRootDept();
		}else{
			rootDept = (DeptInfo) getById(0);
		}
		addItemAndSub(list, null, rootDept, false, -1);
		
		return list;
	}

	/**
	 * 获取可作为指定组织机构org的上级组织机构导航列表
	 * @param deptInfo			当前正在处理的组织机构
	 * @param currentOrg	当前选择组织机构
	 * @param includeDel
	 *            是否包含已删除对象
	 * @return
	 * @throws Exception
	 * 
	 * @param excludeId
	 * @param currentId
	 * @return
	 * @throws Exception
	 */
	public List<DeptInfo> getParentSelectList(Integer excludeId, Integer currentId) throws Exception {
		return getParentSelectList(excludeId, currentId, false, -1);
	}
	
	/**
	 * 获取可作为指定组织机构org的上级组织机构导航列表
	 * @param deptInfo			当前正在处理的组织机构
	 * @param currentOrg	当前选择组织机构
	 * @param includeDel
	 *            是否包含已删除对象
	 * @return
	 * @throws Exception
	 * 
	 * @param excludeId
	 * @param currentId
	 * @return
	 * @throws Exception
	 */
	public List<DeptInfo> getParentSelectList(Integer excludeId, Integer currentId, boolean onlyOrg, int depth) throws Exception {
		List<DeptInfo> list = new ArrayList<DeptInfo>();

		DeptInfo excludeDept = null;
		if (excludeId!=null){
			excludeDept = getById(excludeId); 
		}
		
		DeptInfo currentDept = null;
		if (currentId!=null){
			currentDept = getById(currentId);
		}
		// 当前parent是否有选择
		if (currentDept != null) {
			// 当前parent有选择
			loadParent(currentDept, -1);
			if (currentDept.getParent()!=null){
				loadSubDepts(currentDept.getParent());
				DeptInfo exclude = null;
				for(DeptInfo subDept:currentDept.getParent().getSubDepts()){
					if (!subDept.equals(excludeDept)){
						loadSubDepts(subDept);
					}else{
						exclude = (DeptInfo)subDept;
					}
				}
				if (exclude!=null){
					currentDept.getParent().getSubDepts().remove(exclude);
				}
				loadSubDepts(currentDept);
				exclude = null;
				for(DeptInfo subDept:currentDept.getSubDepts()){
					if (!subDept.equals(excludeDept)){
						loadSubDepts(subDept);
					}else{
						exclude = (DeptInfo)subDept;
					}
				}
				if (exclude!=null){
					currentDept.getSubDepts().remove(exclude);
				}
				List<DeptInfo> parentList = currentDept.getParent().getParentList();
				for(DeptInfo dept:parentList){
					// 添加所有上级组织机构，
					addItem(list, excludeDept, (DeptInfo)dept);
				}
				// 当前选择的组织机构为空，即顶级，遍历所有一级组织机构
				// 添加所有同级组织机构, 如果是当前选择组织机构，还要添加其直属下级
				addItemAndSub(list, excludeDept, (DeptInfo)currentDept.getParent(), onlyOrg, depth);
			}else{
				loadSubDepts(currentDept);
				DeptInfo exclude = null;
				for(DeptInfo subDept:currentDept.getSubDepts()){
					if (!subDept.equals(excludeDept)){
						loadSubDepts(subDept);
					}else{
						exclude = (DeptInfo)subDept;
					}
				}
				if (exclude!=null){
					currentDept.getSubDepts().remove(exclude);
				}
				List<DeptInfo> parentList = currentDept.getParentList();
				for(DeptInfo dept:parentList){
					// 添加所有上级组织机构，
					addItem(list, excludeDept, (DeptInfo)dept);
				}
				// 当前选择的组织机构为空，即顶级，遍历所有一级组织机构
				// 添加所有同级组织机构, 如果是当前选择组织机构，还要添加其直属下级
				addItemAndSub(list, excludeDept, currentDept, onlyOrg, depth);
			}
		} else {
			// 当前选择的组织机构为空，即顶级，遍历所有一级组织机构
			// 添加当前上级所有同级组织机构及其直属下级
			DeptInfo deptRoot = (DeptInfo) getById(0);
			loadSubDepts(deptRoot);
			addItem(list, excludeDept, deptRoot);
			List<DeptInfo> rootList = deptRoot.getSubDepts();
			for (int i = 0; i < rootList.size(); i++) {
				DeptInfo o1 = rootList.get(i);
				if (((DeptInfo)o1).getState() == 1) {
					if (rootList.size() > 1) {
						addItemAndSub(list, excludeDept, (DeptInfo)o1, onlyOrg, 0);
					} else {
						addItemAndSub(list, excludeDept, (DeptInfo)o1, onlyOrg, 1);
					}
				}
			}
		}
		return list;
	}

	/**
	 * 递归加载上级部门
	 * @param deptInfo
	 */
	public void loadParent(DeptInfo deptInfo) {
		loadParent(deptInfo, -1);
	}

	/**
	 * 递归加载上级部门
	 * @param deptInfo
	 */
	public void loadParent(DeptInfo deptInfo, int parentDepth) {
		if (deptInfo!=null&&deptInfo.getPkId()!=null&&deptInfo.getPkId()>0&&deptInfo.getParId()!=null&&(parentDepth==-1||parentDepth>0)){
			DeptInfo parent = getById(deptInfo.getParId());
			deptInfo.setParent(parent);
			loadParent(parent,  parentDepth==-1?-1:parentDepth--);
		}
	}

	public void addItem(List<DeptInfo> list, DeptInfo excludeDept, DeptInfo deptInfo) {
		if (!deptInfo.equals(excludeDept)) {
			list.add(new DeptInfo(deptInfo.getPkId(), getNavName(deptInfo)));
		}
	}

	/**
	 * 
	 * @param list
	 * @param excludeDept
	 * @param o1
	 * @param onlyOrg 只想要组织机构，找到组织机构就不需在找了
	 * @param depth 遍历深度
	 * @throws Exception
	 */
	public void addItemAndSub(List<DeptInfo> list, DeptInfo excludeDept, DeptInfo o1, boolean onlyOrg, int depth)
			throws Exception {
		if (!o1.equals(excludeDept)) {
			list.add(new DeptInfo(o1.getPkId(), getNavName(o1)));
			if (!(o1.isOrganization()&&onlyOrg)&&(depth == -1 || depth > 0)) {
				if (depth > 0) {
					depth--;
				}
				loadSubDepts(o1);
				addSubItem(list, excludeDept, o1.getSubDepts(), onlyOrg, depth);
			}
		}
	}

	public void addSubItem(List<DeptInfo> list, DeptInfo org, List<DeptInfo> sourceList, boolean onlyOrg, int depth)
			throws Exception {
		for (int j = 0; j < sourceList.size(); j++) {
			DeptInfo o2 = (DeptInfo)sourceList.get(j);
			addItemAndSub(list, org, o2, onlyOrg, depth);
		}
	}

	public String getNavName(DeptInfo o) {
		String navName = "";
		List<DeptInfo> list = o.getParentList();
		if (list.size()>0){
			DeptInfo parent;
			for (int i=0;i<list.size()-1;i++) {
				parent = (DeptInfo)list.get(i+1);
				if (parent.isLast()) {
					navName += "　";
				} else {
					navName += "│";
				}
			}
			if (!o.isLast()) { 
				navName += "├";
			} else {
				navName += "└";
			}
		}
		navName += o.getName();
		return navName;
	}
	
	public OrgInfo getParentOrgByDeptId(Integer deptId){
		OrgInfo orgPo = null;
		
		DeptInfo deptInfoPo = getById(deptId);
		if(deptInfoPo!=null){
			loadParent(deptInfoPo);
			for(DeptInfo parent:deptInfoPo.getParentList()){
				if(parent.getOrgId()!=null&&parent.getOrgId()>0){
					orgPo = getOrgInfoDao().getById(parent.getOrgId());
					if(orgPo!=null){
						break;
					}
				}
			}
		}

		return orgPo;
	}
	
	public OrgInfo getOrgInfoById(Integer id){
		return getOrgInfoDao().getById(id);
	}
	
	public OrgInfo saveOrgInfo(OrgInfo orgVo) {
		try {
			if (orgVo.getPkId()==null){
				orgVo.setIdType(0);
				orgVo.setState(1);
				orgVo = getOrgInfoDao().save(orgVo);
			}else{
				orgVo = updateOrgInfo(orgVo);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return orgVo;
	}
	
	public OrgInfo updateOrgInfo(OrgInfo orgVo) {
		return getOrgInfoDao().update(orgVo);
	}
	
	public boolean deleteOrgInfo(OrgInfo orgVo) throws Exception {
		return getOrgInfoDao().delete(orgVo);
	}

	/**
	 * 获取用户 记录
	 * @param index 当前页
	 * @param maxresult 每页数量 
	 * @param 
	 * @return
	 */	
	public QueryResult<OrgInfo> getOrgInfoAll(Integer index,
			Integer maxresult, String name) {
		
		String whererjpql="  1=1";
        List<String> lst = new ArrayList<String>();
        if (name != null && !name.trim().equals(""))
        {
            whererjpql = whererjpql + " and o.name  like ?";
            lst.add("%"+name+"%");
        }
        LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
        orderby.put("pkId","asc");
        return getOrgInfoDao().getScrollData(OrgInfo.class, "pkId", index,
                maxresult, whererjpql, lst.toArray(),orderby);
	}	
	
	/**
	 * 根据机构类型获取机构信息
	 * @param type
	 * @return
	 * @author 舒俊
	 */
	public List<OrgInfo> getOrgInfoByTypeAll(int type){
		OrgInfo u = new OrgInfo();
		u.setState(1);
		return getOrgInfoDao().query(u);
	}
	

	public List<OrgInfo> getOrgInfoAll(){
		OrgInfo u = new OrgInfo();
		u.setState(1);
		return getOrgInfoDao().query(u);
	}	
	
	public List<DeptInfo> getDeptInfoListByOrgid(Integer orgId){
		DeptInfo d = new DeptInfo();
		d.setState(1);
		d.setOrgId(orgId);
		return this.getDeptInfoDao().query(d);
	}

	public OrgInfo getNewOrg(OrgInfo org) {
		OrgInfo newEntity = org;
		
		if (newEntity==null){
			newEntity = new OrgInfo();
		}
		newEntity.setIdType(0);
		newEntity.setState(1);
		
		return newEntity;
	}

	public OrgInfo getByRootDept(DeptInfo deptVo) {
		OrgInfo orgPo = null;
		
		OrgInfo d = new OrgInfo();
		d.setState(1);
		DeptInfo rootDept = null;
		if (deptVo!=null&&deptVo.getOrg()!=null&&deptVo.getOrg().getRootDept()!=null&&deptVo.getOrg().getRootDept().getPkId()!=null){
			rootDept = this.getDeptInfoDao().getById(deptVo.getOrg().getRootDept().getPkId());
		}
		d.setRootDept(rootDept);
		List<OrgInfo> list = this.getOrgInfoDao().query(d);
		if (list!=null&&list.size()>0){
			orgPo = list.get(0);
		}
		
		return orgPo;
	}

	/**
	 * 
	 * @param deptVo
	 * @param create
	 * @return
	 */
	public OrgInfo findOrgInfo(DeptInfo deptVo, boolean create) {
		OrgInfo findOrgInfo = null;

		OrgInfo example = new OrgInfo();
		example.setName(deptVo.getName());
		if (deptVo.getOrg()!=null&&deptVo.getOrg().getName()!=null&&deptVo.getOrg().getName().length()>0){
			example.setName(deptVo.getOrg().getName());
		}
		example.setState(1);
		List<OrgInfo> list = getOrgInfoDao().query(example);
		if (list!=null&&list.size()>0){
			for(OrgInfo org:list){
				if (org.getRootDept()==null||org.getRootDept().getPkId().equals(deptVo.getPkId())){
					findOrgInfo = org;
				}
			}
		}
		if (findOrgInfo==null&&create){
			findOrgInfo = getNewOrg(null);
		}
		
		return findOrgInfo;
	}

	/**
	 * 获取可管理的组织机构树列表
	 * @param currentUser
	 * @throws Exception 
	 */
	public List<DeptInfo> getManagedOrgSelectList(UserInfo currentUser) throws Exception {
		List<DeptInfo> orgTreelist = new ArrayList<DeptInfo>();
		
		Map<Integer, DeptInfo> deptMap = new HashMap<Integer, DeptInfo>();
		if(haveRight(RIGHT_ADMIN_MANAGE, currentUser)){
			//管理员登录获取所有机构信息
			orgTreelist = getOrgTreeList(currentUser);
		}else{
			// 获取用户所属部门列表
			List<DeptInfo> userDepts = AppContextService.getUserOrgService().getUserDepts(currentUser);
			for(DeptInfo userDeptInfo:userDepts){
				loadParent(userDeptInfo, -1);
				DeptInfo orgRootDept = (DeptInfo)userDeptInfo.getOrgRootDept();
				if (orgRootDept!=null&&!deptMap.containsKey(orgRootDept.getPkId())){
					deptMap.put(orgRootDept.getPkId(), orgRootDept);
				}
			}
			orgTreelist = new ArrayList<DeptInfo>();
			for(DeptInfo deptInfo:deptMap.values()){
				orgTreelist.add(deptInfo);
			}
		}
		
		return orgTreelist;
	}

	private List<DeptInfo> getOrgTreeList(UserInfo currentUser) throws Exception {
		List<DeptInfo> orgTreeList = new ArrayList<DeptInfo>();
		orgTreeList = getParentSelectList(null, currentUser.getPkId(), true, 3);
		return orgTreeList;
	}

	private void checkOrgManageRight(UserInfo currentUser) throws Exception {
		if (!haveRight(RIGHT_ORG_MANAGE, currentUser)){
			throw new Exception("你没有管理组织机构的权限！");
		}
	}

	public OrgInfo findByName(String name) {
		OrgInfo result = null;
		
		OrgInfo u = new OrgInfo();
		u.setState(2);
		u.setName(name);
		List<OrgInfo> list = getOrgInfoDao().query(u);
		if (list!=null&&list.size()>0){
			result = list.get(0);
		}
		return result;
	}

	public DeptTypeEnum[] getSubDeptTypes(DeptInfo localDept) {
		DeptTypeEnum[] result;
		if (localDept!=null){
			if (localDept.isOrganization()){
				result = new DeptTypeEnum[]{ DeptTypeEnum.GENERAL, DeptTypeEnum.GROUP};
			}else{
				result = new DeptTypeEnum[]{ DeptTypeEnum.GROUP, DeptTypeEnum.ORG};
			}
		}else{
			result = DeptTypeEnum.values();
		}
		return result;
	}

	/**
	 * 获取远程关联部门树列表 
	 * @return
	 * @throws Exception 
	 */
	public List<Map<String, Object>> getRelevanceDeptTreeList(String relevanceConfig, int depth) throws Exception {
		RTXDeptBean rtxDept = new RTXDeptBean();
		rtxDept.setDeptName("");
		boolean rtxMountSuccess;
		String relevanceType = RelevanceConfig.getRelevanceType(relevanceConfig);
		if ("RTX".equals(relevanceType)){
			// 获取远程组织架构进行装配，腾讯通组织架构
			rtxMountSuccess = mountRtxDeptTree(rtxDept, relevanceConfig);
		}else if ("DingTalk".equals(relevanceType)){
			// 钉钉组织架构
			//获取关联配置
			rtxMountSuccess = mountDingDeptTree(rtxDept, relevanceConfig);
		}else{
			rtxMountSuccess = false;
		}
		List<Map<String, Object>> list = new  ArrayList<Map<String, Object>>();
		if (rtxMountSuccess){
			addList(list, rtxDept, "", depth);
		}

		return list;
	}
	
	public boolean mountRtxDeptTree(RTXDeptBean rtxDept, String relevanceConfig) throws Exception {
		boolean result = false;
		
		RTXClient rtxClient = RTXClient.getInstance(relevanceConfig);
		if(rtxClient!=null){
			RTXDept rDept = rtxClient.getRelevanceDeptTree();
			if (rDept!=null){
				result = true;
				
				Map<Integer,RTXDeptBean> deptMap = new HashMap<Integer,RTXDeptBean>();
				rtxDept.setDeptMap(deptMap);
				deptMap.put(rtxDept.getId(), rtxDept);
				
				rtxDept.setRelevanceId(rDept.getDeptId()==null?null:rDept.getDeptId().longValue());
				mountSubDeptTree(rtxDept, rDept, deptMap);
			}
		}
		
		return result;
	}
	
	public boolean mountDingDeptTree(RTXDeptBean rtxDept, String relevanceConfig) throws Exception {
		boolean result = false;
		
		DingTalkClient dingTalkClient = DingTalkClient.getInstance(relevanceConfig);
		Department department = dingTalkClient.getDeptTree();
		if (department!=null){
			result = true;
			
			Map<Integer,RTXDeptBean> deptMap = new HashMap<Integer,RTXDeptBean>();
			rtxDept.setDeptMap(deptMap);
			deptMap.put(rtxDept.getId(), rtxDept);

			mountSubDeptTree(rtxDept, department, deptMap);
		}
		
		return result;
	}

	/**
	 * 递归装配子部门树
	 * @param rtxDept
	 * @param rDept
	 */
	private void mountSubDeptTree(RTXDeptBean rtxDept, RTXDept rDept, Map<Integer,RTXDeptBean> deptMap) {
		if (rtxDept.getSubDepts()==null){
			rtxDept.setSubDepts(new ArrayList<RTXDeptBean>());
		}else{
			rtxDept.getSubDepts().clear();
		}
		if(rtxDept.getUsers()==null){
			rtxDept.setUsers(new ArrayList<RTXUserBean>());
		}else{
			rtxDept.getUsers().clear();
		}
		if (rDept!=null&&rDept!=null){
			if (rDept.getSubDepts()!=null){
				for(Object dept:rDept.getSubDepts()){
					RTXDept subDept = (RTXDept) dept;
					
					RTXDeptBean rtxSubDept = new RTXDeptBean();
					
					rtxSubDept.setParent(rtxDept);
					
					if(rtxDept.getId()!=null){
						rtxSubDept.setParentId(rtxDept.getId());
					}
					rtxSubDept.setRelevanceId(subDept.getDeptId().longValue());
					rtxSubDept.setDeptName(subDept.getDeptName());
					
					deptMap.put(rtxSubDept.getId(), rtxSubDept);
					
					rtxDept.getSubDepts().add(rtxSubDept);
					mountSubDeptTree(rtxSubDept, (RTXDept) subDept, deptMap);
				}
			}
			if(rDept.getUsers()!=null){
				for(Object user:rDept.getUsers()){
					RTXUserBean rtxUser = new RTXUserBean();
					
					rtxUser.addUserDept(rtxDept);
					rtxUser.setRelevanceId(""+((Department) user).getId());
					rtxUser.setUserName(((RTXUserBean) user).getUserName());
					rtxUser.setName(((Department) user).getName());
					
					rtxDept.getUsers().add(rtxUser);
				}
			}
		}
	}

	/**
	 * 递归装配子部门树
	 * @param rtxDept
	 * @param department
	 */
	private void mountSubDeptTree(RTXDeptBean rtxDept, Department department, Map<Integer,RTXDeptBean> deptMap) {
		if (department!=null){
			if (department.getSubDepartments()!=null){
				if (rtxDept.getSubDepts()==null){
					rtxDept.setSubDepts(new ArrayList<RTXDeptBean>());
				}else{
					rtxDept.getSubDepts().clear();
				}
				for(Department subDept:department.getSubDepartments()){
					RTXDeptBean rtxSubDept = new RTXDeptBean();
					
					rtxSubDept.setParent(rtxDept);
					
					if(rtxDept.getRelevanceId()!=null){
						rtxSubDept.setParentId(rtxDept.getId());
					}
					rtxSubDept.setRelevanceId(subDept.getId());
					rtxSubDept.setDeptName(subDept.getName());
					
					deptMap.put(rtxSubDept.getId(), rtxSubDept);
					
					rtxDept.getSubDepts().add(rtxSubDept);
					
					mountSubDeptTree(rtxSubDept, subDept, deptMap);
				}
			}
			if(department.getMember()!=null){
				if (rtxDept.getUsers()==null){
					rtxDept.setUsers(new ArrayList<RTXUserBean>());
				}else{
					rtxDept.getUsers().clear();
				}
				for(User user:department.getMember()){
					RTXUserBean rtxUser = new RTXUserBean();
					
					rtxUser.setUserName(user.getUserid());
					rtxUser.setName(user.getName());
					
					rtxDept.getUsers().add(rtxUser);
				}
			}
		}
	}
	
	private void addList(List<Map<String, Object>> list, RTXDeptBean rtxDept, String path, int depth) {
		if (rtxDept.getSubDepts()!=null){
			for(Object dept:rtxDept.getSubDepts()){
				RTXDeptBean subDept = (RTXDeptBean) dept;
				addItemAndSub(list, subDept, path, depth);
			}
		}
	}

	private void addItemAndSub(List<Map<String, Object>> list, RTXDeptBean rtxDept, String path, int depth) {
		if (path.length()>0){
			path += "|";
		}
		Map<String, Object> dept = new HashMap<String, Object>();
		dept.put("name", path+rtxDept.getDeptName());
		list.add(dept);
		if (depth>0||depth==-1){
			addList(list, rtxDept, path+rtxDept.getDeptName(), (depth>0?depth-1:-1));
		}
	}

	public void loadUsers(DeptInfo deptInfo) {
		if (deptInfo.getUsers()==null){
			deptInfo.setUsers(new ArrayList<UserInfo>());
		}else{
			deptInfo.getUsers().clear();
		}
		List<UserInfo> list = getUserInfoService().getUsersByDeptId(deptInfo.getPkId());
		for(UserInfo user:list){
			// 加载用户部门
			getUserInfoService().loadUserDepart(user);
			// 设置当前用户部门
			user.setDepart(deptInfo);
			deptInfo.getUsers().add(user);
		}
	}

	/**
	 * 获取以指定部门为根的部门树，
	 * @param rebuild 是否需要重新构建
	 * @throws Exception 
	 */
	@Override
	public DeptInfo getRootDept(Integer id, boolean rebuild, String funcKey, LocalUser currentUser) {
		DeptInfo rootDept = null;
		
		try {
			if(funcKey!=null) {
				if (getRoleInfoService().haveRight(funcKey, (UserInfo) currentUser)){
					if(haveRightRange((UserInfo) currentUser, funcKey, RIGHT_RANGE_ORG_ALL)){
						if (rebuild){
							rootDept = new DeptInfo(id, "组织机构", 0);
							rootDept.setDeptMap(new HashMap<Integer, DeptInfo>());
						}
					}else if(haveRightRange((UserInfo) currentUser, funcKey, RIGHT_RANGE_ORG_ORG)){
						if (rebuild){
							rootDept = new DeptInfo(id, "组织机构", 0);
							rootDept.setDeptMap(new HashMap<Integer, DeptInfo>());
							for(Object ud: currentUser.getUserDepts()){
								DeptInfo userDept = (DeptInfo) ud;
								loadParent(userDept);
								rootDept.getSubDepts().add(userDept.getOrgRootDept());
							}
						}
					}else{
						if (rebuild){
							rootDept = new DeptInfo(id, "组织机构", 0);
							rootDept.setDeptMap(new HashMap<Integer, DeptInfo>());
							for(Object ud: currentUser.getUserDepts()){
								DeptInfo userDept = (DeptInfo) ud;
								loadParent(userDept);
								rootDept.getSubDepts().add(userDept.getOrgRootDept());
							}
						}
					}
				}
			}else{
				if (rebuild){
					rootDept = new DeptInfo(id, "组织机构", 0);
					rootDept.setDeptMap(new HashMap<Integer, DeptInfo>());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return rootDept;
	}

	/**
	 * 获取根部门
	 * @param rebuild 是否需要重新构建
	 * @throws Exception 
	 */
	@Override
	public DeptInfo getRootDept(boolean rebuild, String funcKey, LocalUser currentUser) {
		return getRootDept(0, rebuild, funcKey, currentUser);
	}

	public Page<DeptInfo> manage(Page<DeptInfo> page) {
		DeptInfo parent = (DeptInfo) page.getFindByExample().getParent();
		
		Integer parentId = null;
		if (parent!=null){
			parentId = parent.getPkId();
			if (parentId!=null){
				parent = getById(parentId);
				if(parent!=null&&parent.getParId()!=null){
					parent.setParent(getById(parent.getParId()));
				}
			}else{
				parent = null;
			}
		}
		
		page.getFindByExample().setParent(parent);
		List<DeptInfo> deptInfolist = getSubDeptsByParentId(parentId);
		for(DeptInfo deptInfo:deptInfolist){
			loadRefObjectListMap(deptInfo);
		}
		page.setData(deptInfolist);
		page.setTotalCount(deptInfolist.size());
		
		page.getFindByExample().setParent(parent);
		
		return page;
	}

	@Override
	public void loadRefObjectListMap(DeptInfo deptInfo) {
		loadSubDepts((DeptInfo) deptInfo, -1);
		if (deptInfo.getRefObjectListMap()==null){
			deptInfo.setRefObjectListMap(new HashMap<String,List<? extends Object>>());
		}
		List<IRefObject> serviceList = (List<IRefObject>)AppContextService.findServicesBy(IRefObject.class);
		if (serviceList!=null){
			for (IRefObject service : serviceList){
				Map<String, List<? extends Object>> dd = service.getRefObjectList(deptInfo);
				for(Entry<String, List<? extends Object>> entry:dd.entrySet()){
					deptInfo.getRefObjectListMap().put(entry.getKey(),entry.getValue());
				}
			}
		}
	}

	public List<DeptInfo> getUserDepts(UserInfo currentUser) {
		return getUserOrgService().getUserDepts(currentUser);
	}

	@Override
	public DeptInfo getRootDeptByOrgId(Integer orgId) {
		DeptInfo orgRootDept = null;
		
		OrgInfo org = orgInfoDao.getById(orgId);
		if(org!=null){
			orgRootDept = org.getRootDept();
		}
		
		return orgRootDept;
	}

	/**
	 * 获取部门关系最小范围，暂时还未实际使用
	 * @param deptId
	 * @param currentDept
	 * @return
	 */
	public String getOrgRange(Integer deptId, DeptInfo currentDept) {
		String orgRange = null;
		
		if(currentDept==null||currentDept.getPkId()==null||currentDept.getPkId()==0){
			orgRange = RIGHT_RANGE_ORG_ALL;
		}else{
			if(currentDept.getPkId().intValue()==deptId.intValue()){
				orgRange = RIGHT_RANGE_ORG_DEPT;
			}else{
				loadParent(currentDept);
				DeptInfo deptInfo = getById(deptId);
				loadParent(deptInfo);
				if (currentDept.getOrgId().intValue()==deptInfo.getOrgId().intValue()){
					orgRange = RIGHT_RANGE_ORG_ORG;
				}else{
					orgRange = RIGHT_RANGE_ORG_ALL;
				}
			}
		}
		
		return orgRange;
	}

	@Override
	public List<LocalDept> getOrgRootDeptList() {
		List<LocalDept> list = new ArrayList<LocalDept>();
		
		List<OrgInfo> orgList = getOrgInfoAll();
		for(OrgInfo org:orgList){
			LocalDept rootDept = org.getRootDept();
			if(rootDept!=null){
				list.add(org.getRootDept());
			}
		}
		
		return list;
	}

	@Override
	public List<LocalUser> getAllUsers() {
		List<LocalUser> list = new ArrayList<LocalUser>();
		for(LocalUser localUser:getUserInfoService().getAll()){
			list.add(localUser);
		}
		return list;
	}

	public List<OrgType> getOrgTypeList() {
		List<OrgType> list = orgTypeDao.findAll();
		return list;
	}

	public List<OrgDeptLevel> getOrgDeptLevelList(Integer orgTypeId) throws Exception {
		List<OrgDeptLevel> list = orgDeptLevelDao.findByProperty("orgTypeId", orgTypeId, "level");
		return list;
	}

	@Override
	public String getOrgManageRight() {
		return RIGHT_ORG_MANAGE;
	}

}
